package com.itcanteen.medical.docker.service.impl;

import com.itcanteen.medical.common.constant.CommonStatus;
import com.itcanteen.medical.common.constant.Contstant;
import com.itcanteen.medical.common.constant.Status;
import com.itcanteen.medical.common.constant.Success;
import com.itcanteen.medical.common.exception.AdException;
import com.itcanteen.medical.common.vo.CommonResponse;
import com.itcanteen.medical.docker.entity.Doctor;
import com.itcanteen.medical.docker.entity.FundAccount;
import com.itcanteen.medical.docker.mapper.DoctorMapper;
import com.itcanteen.medical.docker.mapper.FundAccountMapper;
//import com.itcanteen.medical.docker.mapper.WithdrawalMapper;
import com.itcanteen.medical.docker.service.FundAccountService;
import com.itcanteen.medical.docker.util.PhoneUtil;
import com.itcanteen.medical.docker.util.SendSms;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

@Service
@Slf4j
public class FunAccountServiceImpl implements FundAccountService {
    @Autowired
    private FundAccountMapper fundAccountMapper;

    /*@Autowired
    private WithdrawalMapper withdrawalMapper;*/

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * 提现
     * @return
     * @throws AdException
     */
    @Override
    public CommonResponse upd(long userid, Double price) {
//        String code =(String) redisTemplate.boundHashOps("rediscode").get("code");
//
//        if (code == null){
//            return new CommonResponse(-1,"验证码过期！请重新发送验证码！");
//        }
//
//        if (!code.equals(cold)){
//            return new CommonResponse(-1,"验证码错误！请重新输入");
//        }

        Example example = new Example(FundAccount.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("user_id",userid);


        FundAccount account = fundAccountMapper.selectByExample(example).get(0);

        //判断用户是否绑定提现方式
        if (account == null){
            return new CommonResponse(-1,"请绑定提现方式！！！");
        }
        //判断提现金额是否大于余额 如果大于余 则不许提交
        //2000 < 2001
        if (account.getAccount_balance() < price){
            return new CommonResponse(-1,"提现金额大于账户余额！！！");
        }
        if (account.getAccount_balance() >= price){
            account.setAccount_balance(account.getAccount_balance() - price);
        }

        int i = fundAccountMapper.updateByPrimaryKey(account);



        return new CommonResponse(i,"提现成功！将于2小时内到账");
    }


    @Override
    public FundAccount findOne(long userid) {

        Example example = new Example(FundAccount.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("user_id",userid);


        FundAccount account = fundAccountMapper.selectByExample(example).get(0);

        return account;

    }

    /**
     * 发送提现验证码
     * @return
     * @param phone
     */
    @Override
    public CommonResponse sendMsg(String phone){
        int code = new Random().nextInt(9999);

        if(code<1000){
            code+=1000;
        }
        System.out.println(code);

        String message="{\"mobile\":\""+phone+"\",\"code\":\""+code+"\"}";

        log.info("发送消息给："+phone+"code："+code);
        ActiveMQQueue sendMessage = new ActiveMQQueue("sendMessage");
        jmsMessagingTemplate.convertAndSend(sendMessage,message);

        return new CommonResponse(CommonStatus.VALID.getCode(),Success.SuccessMsg.SENDCODE_SUCCESS);
    }

    /**
     * 注销账号
     * @param id
     * @return
     */
    @Override
    public CommonResponse logOut(Long id)  {
        //账户注销 医生注销账号
        //通过id查询
        Doctor doctor = doctorMapper.selectByPrimaryKey(id);

        if(doctor==null){
            //不存在该用户
            return new CommonResponse(CommonStatus.INVALID.getCode(),Contstant.ErrorMsg.NOTNULL);
        }

        if(Status.FAIL.equals(doctor.getStatus())){
            return new CommonResponse(CommonStatus.INVALID.getCode(),Contstant.ErrorMsg.NOTREGISTER_FAILURE);
        }

        //存在该用户 注销账号 更改状态
        doctor.setStatus("1");

        //更新医生账号
        doctor.setUpdateTime(new Date());
        int update = doctorMapper.updateByPrimaryKey(doctor);


        log.info("当前医生信息为："+doctor.toString());

        return new CommonResponse(CommonStatus.VALID.getCode(),Success.SuccessMsg.LOGOUT_SUCCESS);
    }

    /**
     * 发送找回账号验证码
     * @param phone
     */
    @Override
    public CommonResponse verify(String phone){

        boolean mobileNO = PhoneUtil.isMobileNO(phone);

        if(!mobileNO){
           return new CommonResponse(CommonStatus.INVALID.getCode(),Contstant.ErrorMsg.NOMOBILE_FALLER);
        }
        //随机获取四位数
        int code = new Random().nextInt(9999);

        if(code<1000){
            code+=1000;
        }
        redisTemplate.boundHashOps("verifyCode").put(phone,code+"");

        SendSms.sendMag(phone,code+"");

        return new CommonResponse(CommonStatus.VALID.getCode(),Success.SuccessMsg.SENDCODE_SUCCESS,code);
    }

    /**
     * 验证身份 并找回密码
     * @param phone
     * @param code
     * @return
     */
    @Override
    public CommonResponse retrieveAccount(String phone,String code) {
        //获取验证码
        String verifyCode = (String) redisTemplate.boundHashOps("verifyCode").get(phone);

        if(!verifyCode.equals(code)){
            //验证失败
            return new CommonResponse(CommonStatus.INVALID.getCode(),Contstant.ErrorMsg.NOTSENDCODE_FAILURE);
        }

        //获取医生信息
        Doctor doctor = this.getDoctor(phone);

        if(doctor==null){
            //不存在该用户
            return new CommonResponse(CommonStatus.INVALID.getCode(),Contstant.ErrorMsg.NOTREGISTER_FAILURE);
        }
        //获取注销账号时间
        Date logOutTime = doctor.getUpdateTime();

        Calendar instance = Calendar.getInstance();

        instance.setTime(logOutTime);

        //逾期时间
        instance.add(Calendar.DAY_OF_WEEK,7);

        Date overdue=instance.getTime();

        if(new Date().after(overdue)){
            //判断时间是否逾期
            return new CommonResponse(CommonStatus.INVALID.getCode(),Contstant.ErrorMsg.OVERDUE_FAILURE);
        }

        //更改时间
        doctor.setStatus("0");
        doctor.setUpdateTime(new Date());
        doctorMapper.updateByPrimaryKey(doctor);

        return new CommonResponse(CommonStatus.VALID.getCode(),Success.SuccessMsg.RETRIEVE);
    }

    /**
     * 查询医生
     * @param
     * @return
     */
    private Doctor getDoctor(String phone){

        Example example = new Example(Doctor.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andLike("phone","%"+phone+"%");
        return  doctorMapper.selectByExample(example).get(0);
    }

    /*public static void main(String[] args) {

        Date date = new Date();
        System.out.println(date);
        Calendar instance = Calendar.getInstance();

        instance.setTime(date);

        instance.add(Calendar.DAY_OF_WEEK,17);
        System.out.println("111");
        System.out.println(instance.getTime().toLocaleString());
    }
*/
    /*public void addWithdrawal(FundAccount fundAccount,Double price,String pay){
        //成功提现 新增提现记录
        Withdrawal withdrawal = new Withdrawal();

        //使用雪花算法生成订单号
        withdrawal.setOrderId(new IdWorker().nextId());

        //设置用户ID
        withdrawal.setUserId(fundAccount.getUser_id());

        //设置提现金额
        withdrawal.setMonery(price);

        //支付方式
        withdrawal.setPlatform(fundAccount.getPayType());

        //状态 0：可使用 1：禁止使用
        withdrawal.setState("0");

        //操作类型 1充值，2提现 默认为提现
        withdrawal.setOperationType(pay);

        //订单生成时间
        withdrawal.setCreationTime(new Date());

        withdrawalMapper.insert(withdrawal);
    }*/
}
